package com.example.petplanet.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.KeySpec;
import java.util.*;

public class SecureEncryptionUtil {

    private static final String CHARSET = "UTF-8";
    private static final int ITERATION_COUNT = 65536;
    private static final int KEY_LENGTH = 256; // AES 256位密钥

    // 使用PBKDF2从appId和appSecret生成密钥
    public static SecretKeySpec generateKey(String appId, String appSecret) throws Exception {
        KeySpec spec = new PBEKeySpec(appId.toCharArray(), appSecret.getBytes(CHARSET), ITERATION_COUNT, KEY_LENGTH);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        byte[] keyBytes = factory.generateSecret(spec).getEncoded();
        return new SecretKeySpec(keyBytes, "AES");
    }

    // 加密
    public static String encrypt(String data, String appId, String appSecret) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKeySpec key = generateKey(appId, appSecret);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes(CHARSET));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 解密
    public static String decrypt(String encryptedData, String appId, String appSecret) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKeySpec key = generateKey(appId, appSecret);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedBytes, CHARSET);
    }

//    public static void main(String[] args) {
//        try {
//            String appId = "wx6ea1b3d58ba5825e";
//            String appSecret = "de0bea9331af57df9b12decad68318d4";
//            String  id= "6";
//
//            // 需要加密的数据
//            String data = id;
//            System.out.println("需要加密的数据: " + data);
//
//            // 加密
//            String encryptedData = encrypt(data, appId, appSecret);
//            System.out.println("加密的数据: " + encryptedData);
//
//            // 解密
//            String decryptedData = decrypt(encryptedData, appId, appSecret);
//            System.out.println("解密的数据: " + decryptedData);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
